import { AMAP_CONFIG, validateApiKey, getAmapApiUrl } from "@/config/amap";

let amapPromise = null;

export function loadAmapJs(key = AMAP_CONFIG.apiKey) {
  if (window.AMap) return Promise.resolve(window.AMap);

  if (!amapPromise) {
    amapPromise = new Promise((resolve, reject) => {
      // 检查API Key
      if (!validateApiKey(key)) {
        reject(new Error("请配置有效的高德地图API Key"));
        return;
      }

      const script = document.createElement("script");
      script.src = getAmapApiUrl(key);
      script.async = true;
      
      script.onload = () => {
        // 脚本加载完成，等待AMap对象可用
        const checkAMap = () => {
          if (window.AMap) {
            resolve(window.AMap);
          } else {
            setTimeout(checkAMap, 50);
          }
        };
        checkAMap();
      };
      
      script.onerror = () => {
        reject(new Error("高德地图脚本加载失败，请检查网络连接或API Key"));
      };
      
      document.head.appendChild(script);

      // 设置超时
      setTimeout(() => {
        if (!window.AMap) {
          reject(new Error("高德地图加载超时，请检查网络连接"));
        }
      }, 15000);
    });
  }

  return amapPromise;
}
